<template>
  <div id="detail">
    <NavBar class="detail-nav">
      <div slot="left" class="back" @click="goBack">
        <img src="~assets/img/common/back.svg" alt="" />
      </div>
      <div slot="center" class="title">
        <TabControl :titles="titles" @tabClick="tabClick" ref="tab">
        </TabControl>
      </div>
    </NavBar>
    <Scroll class="content" ref="scroll" @scroll="contentScroll">
      <Carsouel :list="topImages" />
      <DetailBaseInfo :goods="goods" />
      <DetailShopInfo :shop="shop" />
      <DetailGoodsInfo :detail-info="detailInfo" @imageLoad="imageLoad" />
      <DetailParamInfo ref="params" :param-info="paramInfo" />
      <DetailCommentInfo ref="comment" :comment-info="commentInfo" />
      <GoodsList ref="recommend" :goods="recommends" @imageLoad="imageLoad" />
    </Scroll>
    <DetailBottom
      @addCart="addCart"
      @handleCollect="handleCollect"
      :iid="iid"
    />
    <BackTop v-show="isShowBackTop" @click.native="backTop" />
  </div>
</template>

<script>
import { backTopMixin } from "@/common/mixin";
import debounce from "lodash/debounce";
import { getDetail, Shop, Goods, GoodsParam, getRecommend } from "@/api/detail";
import DetailBaseInfo from "./DetailBaseInfo";
import DetailShopInfo from "./DetailShopInfo";
import DetailGoodsInfo from "./DetailGoodsInfo";
import DetailParamInfo from "./DetailParamInfo";
import DetailCommentInfo from "./DetailCommentInfo";
import DetailBottom from "./DetailBottom";
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Detail",
  mixins: [backTopMixin],
  data() {
    return {
      iid: "",
      currentIndex: 0,
      topImages: [],
      titles: ["商品", "参数", "评论", "推荐"],
      goods: {},
      detailInfo: {},
      shop: {},
      paramInfo: {},
      commentInfo: {},
      recommends: [],
      paramtop: 0,
      recommendtop: 0,
      commenttop: 0,
      getThemeTopY: null,
      themeTopYs: [],
    };
  },
  components: {
    DetailBaseInfo,
    DetailShopInfo,
    DetailGoodsInfo,
    DetailParamInfo,
    DetailCommentInfo,
    DetailBottom,
  },
  created() {
    this.iid = this.$route.params.id;
    this.getDetail(this.iid);
    this.getReco();
    this.getThemeTopY = debounce(() => {
      this.themeTopYs = [];

      this.themeTopYs.push(0);
      this.themeTopYs.push(this.$refs.params.$el.offsetTop);
      this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
      this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
      this.themeTopYs.push(Number.MAX_VALUE);
      // console.log(this.themeTopYs);
    });
  },

  mounted() {
    // 4.给getThemeTopY赋值
    //goods是一个对象 this.title =data.itemInfo.title
    // this.desc = itemInfo.desc
    // this.realPrice = itemInfo.lowNowPrice
    //   this.goods = new Goods(
    //     data.itemInfo,
    //     data.columns,
    //     data.shopInfo.services
    //   );
  },
  methods: {
    handleCollect() {
      let product = {};
      product.image = this.topImages[0];
      product.title = this.goods.title;
      product.desc = this.goods.desc;
      product.price = this.goods.realPrice;
      product.iid = this.iid;

      this.$store.dispatch("addCollect", product);
    },
    addCart() {
      this.$message.success("加入成功");
      this.$toast.Show("添加成功");
      let cart = JSON.parse(sessionStorage.getItem("cart")) || [];
      let oldpro = cart.find((v) => v.iid == this.iid);
      // 1.获取购物车需要展示的信息
      let product = {};
      product.image = this.topImages[0];
      product.title = this.goods.title;
      product.desc = this.goods.desc;
      product.price = this.goods.realPrice;
      product.iid = this.iid;
      if (!oldpro) {
        this.$set(product, "num", 1);
        // this.GoodsInfo.num = 1;
        console.log("first");
        this.$set(product, "checked", true);
        cart.push(product);
      } else {
        oldpro.num++;
        // cart[index].num++;
      }
      this.$store.dispatch("addStoreCart", product).then((res) => {
        console.log(res);
      });
      sessionStorage.setItem("cart", JSON.stringify(cart)) || [];
    },
    goBack() {
      // this.$router.go(-1)
      this.$router.back();
    },
    getDetail(id) {
      getDetail(id).then((res) => {
        // 1.获取顶部的图片轮播数据
        console.log(res);
        const data = res.result;
        console.log(data);
        this.topImages = data.itemInfo.topImages;
        // 2.获取商品信息
        this.goods = new Goods(
          data.itemInfo,
          data.columns,
          data.shopInfo.services
        );

        // 3.创建店铺信息的对象
        this.shop = new Shop(data.shopInfo);

        // 4.保存商品的详情数据
        this.detailInfo = data.detailInfo;

        // 5.获取参数的信息,构造函数
        this.paramInfo = new GoodsParam(
          data.itemParams.info,
          data.itemParams.rule
        );
        //   const info = data.itemInfo;

        if (data.rate.cRate !== 0) {
          this.commentInfo = data.rate.list[0];
        }
      });
    },
    getReco() {
      getRecommend().then((res) => {
        this.recommends = res.data.list;
      });
    },
    imageLoad() {
      this.$refs.scroll.refresh();
      this.getThemeTopY(); //图片加载完
    },

    // 2.获取商品信息
    tabClick(index) {
      this.currentIndex = index;

      this.$refs.scroll.scrollTo(0, -this.themeTopYs[index], 0);
    },

    contentScroll(position) {
      // console.log( Math.round(Math.abs(pos.y)));
      const positonY = -position.y;
      for (let i = 0; i <= this.themeTopYs.length; i++) {
        if (
          this.currentIndex !== i &&
          positonY >= this.themeTopYs[i] &&
          positonY < this.themeTopYs[i + 1]
        ) {
          this.currentIndex = i;
          this.$refs.tab.currentIndex = this.currentIndex;
        }
      }
      // 1.判断BackTop是否显示
      this.isShowBackTop = positonY > 1000;
      // let index = this.themeTopYs.findIndex((v) => v == positonY);
      // if (index !== -1) {
      //   console.log(positonY);
      //   console.log(index);
      //   this.currentIndex = index;
      // }

      // this.$refs.tab.currentIndex=index
    },
  },
};
</script>

<style lang="less" scoped>
#detail {
  position: relative;

  background-color: #fff;
  height: 100vh;
}

.detail-nav {
  background-color: #fff;
  position: relative;
  z-index: 9;
}

.content {
  height: calc(100% - 44px);
}
</style>
